<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Service\AftersaleService;
use App\Service\AftersaleSetService;
use App\Service\AreainfoService;
use App\Service\FlyShopService;
use App\Service\ShopDeliveryConfigService;
use App\Service\ShopOrderService;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 商家订单管理
 * Class ShopOrderController
 * @package App\Controller
 */
class ShopOrderController extends AbstractController
{

    /**
     * @Inject
     * @var AreainfoService
     */
    private $areaInfo;

    /**
     * @Inject
     * @var AftersaleSetService
     */
    private $orderSet;

    /**
     * @Inject
     * @var FlyShopService
     */
    private $shop;

    /**
     * @Inject
     * @var ShopOrderService
     */
    private $shopOrder;

    /**
     * 获取店铺ID
     * @param bool $get
     * @return int|ResponseInterface
     */
    private function get_shop_id($get = false)
    {
        $user_id = (int)$this->request->getHeaderLine('admin_id') ?? 0;
        $my_shop = $this->shop->getMyShop($user_id);
        if (!$get && empty($my_shop)) {
            throw new BusinessException(ErrorCode::NORMAL_ERROR, '未获取到店铺信息');
        }
        return $my_shop['id'];
    }

    /**
     * 获取订单列表
     * @return ResponseInterface
     */
    public function orderList()
    {
        $shop_id = $this->get_shop_id();
        if (!$shop_id) {
            return $this->jsonResponse->success([], '店铺不存在');
        }
        $params = $this->request->all();
        // 订单类型查询
        $type = (empty($params['type']) || $params['type'] == 2) ? 2 : 1;
        // 订单状态查询
        $status = $type == 2 ? ((empty($params['status']) || !in_array($params['status'], [1, 2, 3, 4, 5, 6, 7, 8])) ? 1 : $params['status']) : (empty($params['status']) || !in_array($params['status'], [1, 5, 6, 7]) ? 1 : $params['status']);
        $keyword = empty($params['keyword']) ? "" : $params['keyword'];
        $page = $this->paginate($this->shopOrder->getList($shop_id, $type, (int)$status, $keyword));
        $list = $page->toArray();

        $list['type'] = $type;
        $list['status'] = $status;

        $order_set = $this->orderSet->getTimeTypeSet(2);
        foreach ($list['data'] as &$datum) {
            $datum['virtual_form_info_arr'] = empty($datum['virtual_form_info']) ? [] : json_decode($datum['virtual_form_info'], true);
            $sku_name = "";
            $logo = "";
            if (in_array($datum['order_style'], [2])) {
                $sku_name .= date("m月d日,H:i", $datum['virtual_form_info_arr']['date_time']) . ',' . $datum['virtual_form_info_arr']['people_num'] . "人," . ($datum['virtual_form_info_arr']['is_vip'] ? "包间" : "大厅");
                $logo = $datum['virtual_form_info_arr']['logo'] ?? "";
            }
            $datum['sku_name'] = $sku_name;
            $datum['logo'] = $logo;
            // 用户地址
            $datum['address_arr'] = $this->areaInfo->getFullAddress($datum['with_address_info']['street_id'] ?? 0);
            $datum['is_outer'] = 0;
            $datum['outer_time'] = 0;
            $datum['outer_time_str'] = "";
            // 已支付-未发货
            if ($datum['is_pay'] == 1 &&
                in_array($datum['delivery_type'], [ShopDeliveryConfigService::TYPE_EXPRESS, ShopDeliveryConfigService::TYPE_LOCAL])
                && empty($datum['delivery_id'])) {
                // 判断是否超时
                if ($datum['delivery_type'] == ShopDeliveryConfigService::TYPE_LOCAL) {
                    if (!empty($datum['date_time'])) {
                        if ($datum['date_time'] < time()) {
                            // 超时时长
                            $datum['outer_time'] = time() - $datum['date_time'];
                            $datum['is_outer'] = 1;
                        } else {
                            // 剩余配送时长
                            $datum['outer_time'] = $datum['date_time'] - time();
                        }
                        $outer_time_arr = Common::formatSecondDuration($datum['outer_time']);
                        $datum['outer_time_str'] = $outer_time_arr['day'] . "天" . $outer_time_arr['hour'] . "小时" . $outer_time_arr['min'] . "分";
                    }
                } else {
                    $time_sets = array_column($order_set, 'days', 'time_type');
                    $send_set = $time_sets[AftersaleSetService::TYPE_DO] ?? 0;
                    if (!empty($send_set)) {
                        $outer_time = time() - ($datum['paid_time'] + (86400 * $send_set));
                        if ($send_set != -1) {
                            $datum['outer_time'] = $outer_time;
                            // 已超时
                            if ($outer_time > 0) {
                                // 已超时
                                $datum['is_outer'] = 1;
                                $outer_time_arr = Common::formatSecondDuration($datum['outer_time']);
                            } else {
                                // 请在**时间内发货
                                $outer_time_arr = Common::formatSecondDuration(abs($datum['outer_time']));
                            }
                            $datum['outer_time_str'] = $outer_time_arr['day'] . "天" . $outer_time_arr['hour'] . "小时" . $outer_time_arr['min'] . "分";
                        }
                    }
                }
            }
        }
        return $this->jsonResponse->success($list, 'ok!');
    }

    /**
     * 用户提货核销
     * @return ResponseInterface
     */
    public function receiveBySelf()
    {
        $shop_id = $this->get_shop_id();
        if (!$shop_id) {
            return $this->jsonResponse->success([], '店铺不存在');
        }
        $order_sn = (string)$this->request->input('order_sn', '');
        $type = (int)$this->request->input('type', 0);
        $charge_code = (int)$this->request->input('charge_code', 0);
        $re = $this->shopOrder->receiveBySelf($shop_id, $order_sn, $type, $charge_code);
        if (!$re) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        return $this->jsonResponse->success([], '操作成功');
    }

    /**
     * 虚拟产品发货
     * @return ResponseInterface
     */
    public function virtualSend()
    {
        $shop_id = $this->get_shop_id();
        if (!$shop_id) {
            return $this->jsonResponse->success([], '店铺不存在');
        }
        $order_sn = (string)$this->request->input('order_sn', '');
        $re = $this->shopOrder->virtualSend($shop_id, $order_sn);
        if (!$re) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        return $this->jsonResponse->success([], '操作成功');
    }

    /**
     * 获取订单详情
     * @return ResponseInterface
     */
    public function getOrderDetails()
    {
        $shop_id = $this->get_shop_id();
        if (!$shop_id) {
            return $this->jsonResponse->success([], '店铺不存在');
        }
        $order_id = (int)$this->request->input('order_id', 0);
        $return = $this->shopOrder->getOrderDetails($order_id, $shop_id);
        if (empty($return)) {
            return $this->jsonResponse->success([], "订单不存在");
        }
        // 用户地址
        $order_set = $this->orderSet->getTimeTypeSet(2);
        $return['address_arr'] = $this->areaInfo->getFullAddress($return['with_address_info']['street_id'] ?? 0);
        $return['is_outer'] = 0;
        $return['outer_time'] = 0;
        $return['outer_time_str'] = "";
        $return['virtual_form_info_arr'] = empty($return['virtual_form_info']) ? [] : json_decode($return['virtual_form_info'], true);

        $sku_name = "";
        $logo = "";
        if (in_array($return['order_style'], [2])) {
            $sku_name .= date("m月d日,H:i", $return['virtual_form_info_arr']['date_time']) . ',' . $return['virtual_form_info_arr']['people_num'] . "人," . ($return['virtual_form_info_arr']['is_vip'] ? "包间" : "大厅");
            $logo = $return['virtual_form_info_arr']['logo'] ?? "";
        }
        $return['sku_name'] = $sku_name;
        $return['logo'] = $logo;

        $food_outer = 0;
        $food_remaining = "";
        // 美食订单
        if ($return['order_style'] == 3) {
            $food_time_arr = Common::formatSecondDuration(abs($return['virtual_form_info_arr']['date_time'] - time()));
            $food_outer = $return['virtual_form_info_arr']['date_time'] - time() > 0 ? 0 : 1;
            $food_remaining = ($food_outer == 1 ? "已超时：" : "剩余时间：") . ($food_time_arr['day'] ?? 0) . "天" . ($food_time_arr['hour'] ?? 0) . "小时" . ($food_time_arr['min'] ?? 0) . "分";
        }
        $return['food_outer'] = $food_outer;
        $return['food_remaining'] = $food_remaining;

        // 已支付-未发货
        if ($return['is_pay'] == 1 &&
            in_array($return['delivery_type'], [ShopDeliveryConfigService::TYPE_EXPRESS, ShopDeliveryConfigService::TYPE_LOCAL])
            && empty($return['delivery_id'])) {
            // 配送超时
            if ($return['delivery_type'] == ShopDeliveryConfigService::TYPE_LOCAL) {
                if (!empty($return['date_time'])) {
                    if ($return['date_time'] < time()) {
                        // 超时时长
                        $return['outer_time'] = time() - $return['date_time'];
                        $return['is_outer'] = 1;
                    } else {
                        // 剩余配送时长
                        $return['outer_time'] = $return['date_time'] - time();
                    }
                    $outer_time_arr = Common::formatSecondDuration($return['outer_time']);
                    $return['outer_time_str'] = $outer_time_arr['day'] . "天" . $outer_time_arr['hour'] . "小时" . $outer_time_arr['min'] . "分";
                }
            } else {
                // 发货超时
                $time_sets = array_column($order_set, 'days', 'time_type');
                $send_set = $time_sets[AftersaleSetService::TIME_TYPE_ORDER_SEND] ?? 0;
                if (!empty($send_set)) {
                    $outer_time = time() - ($return['paid_time'] + (86400 * $send_set));
                    if ($send_set != -1) {
                        $return['outer_time'] = $outer_time;
                        // 已超时
                        if ($outer_time > 0) {
                            // 已超时
                            $return['is_outer'] = 1;
                            $outer_time_arr = Common::formatSecondDuration($return['outer_time']);
                        } else {
                            // 请在**时间内发货
                            $outer_time_arr = Common::formatSecondDuration(abs($return['outer_time']));
                        }
                        $return['outer_time_str'] = $outer_time_arr['day'] . "天" . $outer_time_arr['hour'] . "小时" . $outer_time_arr['min'] . "分";
                    }
                }
            }
        }
        return $this->jsonResponse->success($return);
    }

    /**
     * 获取商家搜索选项
     * @return ResponseInterface
     */
    public function getSearchTag()
    {
        $shop_id = $this->get_shop_id();
        if (empty($shop_id)) {
            return $this->jsonResponse->success([], '未登录');
        }
        // 默认待处理 1待处理 2订单 3售后单
        $tag = (int)$this->request->input('tag', 1);

        return $this->jsonResponse->success($this->shopOrder->getSearchTag($shop_id, $tag), 'success');
    }

    /************************************** 售后 **************************************/

    /**
     * 获取售后单列表
     * @return ResponseInterface
     */
    public function aftersaleList()
    {
        $shop_id = $this->get_shop_id();
        $params = $this->request->all();
        // 售后类型
        $type = (empty($params['type']) || $params['type'] == 3) ? 3 : 1;
        // 售后待处理状态
        $status = $type == 3 ? (empty($params['status']) || !in_array($params['status'], [1, 2, 3]) ? 1 : $params['status']) : (empty($params['status']) || !in_array($params['status'], [2, 3, 4]) ? 2 : $params['status']);
        echo $type . "-----" . $status;
        $keyword = empty($params['keyword']) ? "" : $params['keyword'];
        $page = $this->paginate($this->shopOrder->getList($shop_id, $type, (int)$status, $keyword));
        $list = $page->toArray();
        $list['type'] = $type;
        $list['status'] = $status;
        $af_sets = $this->orderSet->getTimeTypeSet();
        $time_type_duration = array_column($af_sets, 'days', 'time_type');
        // 判断处理时限
        foreach ($list['data'] as &$datum) {

            if ($datum['af_order_style'] == 2) {
                $arr = empty($datum['with_order']['virtual_form_info']) ? [] : json_decode($datum['with_order']['virtual_form_info'], true);
                $datum['sku_img'] = empty($arr) ? "" : ($arr['logo'] ?? "");
                $datum['sku_name'] = empty($arr) ? "" : (date("m月d日,H:i", $arr['date_time']) . ',' . $arr['people_num'] . "人," . ($arr['is_vip'] ? "包间" : "大厅"));
            }

            // 售后处理时限
            if ($datum['af_status'] == AftersaleService::STATUS_WAIT_CHECK) {
                if (!empty($time_type_duration[AftersaleSetService::TYPE_AFTERSALE_APPLY])) {
                    $do_time = $datum['apply_time'] + $time_type_duration[AftersaleSetService::TYPE_AFTERSALE_APPLY] * 86400 - time();
                    // 未超时
                    if ($do_time > 0) {
                        $datum['is_outer'] = 0;
                        $datum['outer_time'] = $do_time;
                    } else {
                        $datum['is_outer'] = 1;
                        $datum['outer_time'] = abs($do_time);
                    }
                    $outer_time_arr = Common::formatSecondDuration($datum['outer_time']);
                    $datum['outer_time_str'] = $outer_time_arr['day'] . "天" . $outer_time_arr['hour'] . "小时" . $outer_time_arr['min'] . "分";

                }
                // 自动退款时限
            } elseif ($datum['af_status'] == AftersaleService::STATUS_CHECKED && !empty($datum['user_response_time'])) {
                if (!empty($time_type_duration[AftersaleSetService::TIME_TYPE_AUTO_REFUND])) {
                    $do_time = $datum['check_time'] + $time_type_duration[AftersaleSetService::TIME_TYPE_AUTO_REFUND] * 86400 - time();
                    // 未超时
                    if ($do_time > 0) {
                        $datum['is_outer'] = 0;
                        $datum['outer_time'] = $do_time;
                    } else {
                        $datum['is_outer'] = 1;
                        $datum['outer_time'] = abs($do_time);
                    }
                    $outer_time_arr = Common::formatSecondDuration($datum['outer_time']);
                    $datum['outer_time_str'] = $outer_time_arr['day'] . "天" . $outer_time_arr['hour'] . "小时" . $outer_time_arr['min'] . "分";
                }
            }
        }
        $params = $this->request->all();
        $list['type'] = !isset($params['type']) ? 1 : (!in_array($params['type'], [1, 2, 3]) ? 1 : $params['type']);
        $list['status'] = !isset($params['status']) ? 1 : (!in_array($params['status'], [1, 2, 3, 4, 5, 6, 7, 8]) ? 1 : $params['status']);
        return $this->jsonResponse->success($list, 'ok!');
    }

    /**
     * 商家售后单详情
     * @return ResponseInterface
     */
    public function aftersaleDetails()
    {
        $shop_id = $this->get_shop_id();
        $af_sn = (string)$this->request->input('af_sn', '');
        $details = $this->shopOrder->afDetails($shop_id, $af_sn);
        if (empty($details)) {
            return $this->jsonResponse->success([], '售后单不存在');
        }
        $details['is_outer'] = 0;
        $details['outer_time'] = 0;
        $details['outer_time_str'] = "";
        $af_sets = $this->orderSet->getTimeTypeSet();
        $time_type_duration = array_column($af_sets, 'days', 'time_type');

        if ($details['af_order_style'] == 2) {
            $arr = empty($details['with_order']['virtual_form_info']) ? [] : json_decode($details['with_order']['virtual_form_info'], true);
            $details['sku_img'] = empty($arr) ? "" : ($arr['logo'] ?? "");
            $details['sku_name'] = empty($arr) ? "" : (date("m月d日,H:i", $arr['date_time']) . ',' . $arr['people_num'] . "人," . ($arr['is_vip'] ? "包间" : "大厅"));
        }

        // 售后处理时限
        if ($details['af_status'] == AftersaleService::STATUS_WAIT_CHECK) {
            if (!empty($time_type_duration[AftersaleSetService::TYPE_AFTERSALE_APPLY])) {
                $do_time = $details['apply_time'] + $time_type_duration[AftersaleSetService::TYPE_AFTERSALE_APPLY] * 86400 - time();
                // 未超时
                if ($do_time > 0) {
                    $details['is_outer'] = 0;
                    $details['outer_time'] = $do_time;
                } else {
                    $details['is_outer'] = 1;
                    $details['outer_time'] = abs($do_time);
                }
                $outer_time_arr = Common::formatSecondDuration($details['outer_time']);
                $details['outer_time_str'] = $outer_time_arr['day'] . "天" . $outer_time_arr['hour'] . "小时" . $outer_time_arr['min'] . "分";

            }
            // 自动退款时限
        } elseif ($details['af_status'] == AftersaleService::STATUS_CHECKED && !empty($details['user_response_time'])) {
            if (!empty($time_type_duration[AftersaleSetService::TIME_TYPE_AUTO_REFUND])) {
                $do_time = $details['check_time'] + $time_type_duration[AftersaleSetService::TIME_TYPE_AUTO_REFUND] * 86400 - time();
                // 未超时
                if ($do_time > 0) {
                    $details['is_outer'] = 0;
                    $details['outer_time'] = $do_time;
                } else {
                    $details['is_outer'] = 1;
                    $details['outer_time'] = abs($do_time);
                }
                $outer_time_arr = Common::formatSecondDuration($details['outer_time']);
                $details['outer_time_str'] = $outer_time_arr['day'] . "天" . $outer_time_arr['hour'] . "小时" . $outer_time_arr['min'] . "分";
            }
        }

        return $this->jsonResponse->success($details, 'ok!');
    }

    /**
     * 售后单审核
     * @return ResponseInterface
     */
    public function aftersaleCheck()
    {
        $shop_id = $this->get_shop_id();
        $af_sn = (string)$this->request->input('af_sn', '');
        $act = (int)$this->request->input('act', '');
        $af_reason = (string)$this->request->input('af_reason');
        $addr_id = (int)$this->request->input('addr_id', 0);
        $back_delivery = (int)$this->request->input('is_back_delivery', 0);
        $back_coupon = (int)$this->request->input('is_back_coupon', 1);
        $res = $this->shopOrder->aftersaleCheck($shop_id, $af_sn, $act, $addr_id, $back_delivery, $back_coupon, $af_reason);
        if (!$res) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, 'fail');
        }
        return $this->jsonResponse->success([], 'Success');
    }

    /**
     * 商家退款操作
     * @return ResponseInterface
     */
    public function refund()
    {
        $shop_id = $this->get_shop_id();
        $af_sn = (string)$this->request->input('af_sn', '');
        // 默认都不退
        $back_delivery = (int)$this->request->input('is_back_delivery', 1);
        $back_coupon = (int)$this->request->input('is_back_coupon', 1);
        $res = $this->shopOrder->afRefund($shop_id, $af_sn, $back_coupon, $back_delivery);
        if (!$res) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, 'fail');
        }
        return $this->jsonResponse->success([], 'Success');
    }

    /**
     * 商家自行发货配送
     * @return ResponseInterface
     */
    public function localSelfSend(): ResponseInterface
    {
        $shop_id = $this->get_shop_id();
        $order_id = (int)$this->request->input('order_id', 0);
        if (!$this->shopOrder->localSelfSend($order_id, $shop_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '操作失败');
        }
        return $this->jsonResponse->success([], '操作成功');
    }
}